package arrayProblem;

/**
 * 35.搜索插入位置
 * 给定一个排序数组和一个目标值，在数组中找到目标值，并返回其索引。如果目标值不存在于数组中，返回它将会被按顺序插入的位置。
 * 输入: nums = [1,3,5,6], target = 5
 * 输出: 2
 */
public class SearchForLocation {
    public static void main(String[] args) {
        int[] nums = {1, 3, 5, 6};
        SearchForLocation searchForLocation = new SearchForLocation();
        System.out.println(searchForLocation.searchInsert(nums, 5));
    }
//    public int searchInsert(int[] nums, int target) {
//        int length=nums.length;
//        for (int i = 0; i < length; i++) {
//            if(nums[i]==target){
//                return i;
//            }
//        }
//        return 0;
//    }

    public int searchInsert(int[] nums, int target) {
        int n = nums.length;
        int left = 0, right = n - 1, ans = n;
        while (left <= right) {
            int mid = ((right - left) >> 1) + left;
            if (target <= nums[mid]) {
                ans = mid;
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return ans;
    }
}
